﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Atmk.WaterMeter.MIS.Commons;
using Atmk.WaterMeter.MIS.Commons.ViewModels;
using Atmk.WaterMeter.MIS.Commons.ViewModels.Area;
using Atmk.WaterMeter.MIS.Commons.ViewModels.District;
using Atmk.WaterMeter.MIS.TestForm.Common;
using Atmk.WaterMeter.MIS.TestForm.Common.Utils;
using Atmk.WaterMeter.MIS.TestForm.Views.XiangZhanAo.TokenHelper;
using Common.Logging;
using Microsoft.Build.Tasks;
using Newtonsoft.Json;
using NKnife.IoC;
using RestSharp;
using WeifenLuo.WinFormsUI.Docking;

namespace Atmk.WaterMeter.MIS.TestForm.Views.XiangZhanAo
{
    public partial class TestTreeView : DockContent
    {
        private static readonly ILog _Logger = LogManager.GetLogger<TestTreeView>();
        public TestTreeView()
        {
            InitializeComponent();
            BindSite();
            BindClick();
            _TreeView.NodeMouseClick += (s, e) =>
            {
                propertyGrid1.SelectedObject = e.Node.Tag;
            };
        }

        private void BindClick()
        {
            _GetTreeButton.Click += (s, e) => { GetTreeDatas(); };
            _AddDistrictButton.Click += (s, e) =>
            {
                if (!(_TreeView.SelectedNode.Tag is DistrictNode node)) return;
                new AddDistrict(node, _ProjecCombox.SelectedValue.ToString()).ShowDialog();
                GetTreeDatas();
            };
            _DeleteButton.Click += (s, e) =>
            {
                if (!(_TreeView.SelectedNode.Tag is DistrictNode node)) return;
                if (node.nodeType != "branch") return;
                DeleteDistrict(node);
                GetTreeDatas();
            };
            _SelectNodeInfo.Click += (s, e) =>
            {
                if (!(_TreeView.SelectedNode.Tag is DistrictNode node)) return;
                GetNodeInfo(node);
            };
        }

        private void GetNodeInfo(DistrictNode node)
        {
            GetTreeDatas(node.id);
        }

        private void GetTreeDatas(string id="")
        {
            var kernel = DI.Get<Kernel>();
            var resoure = UrlManager.GetTreeNodes + (id.Length > 0 ? $"/{id}" : "");
            var request = new RestRequest(resoure, Method.GET);
            var token = ChangeToken(kernel.Token);
            request.AddHeader("X-Token", token);
            kernel.Client.ExecuteAsync(request, response =>
            {
                var data = response.Content;
                try
                {
                    _Logger.Debug(data);
                    var result = JsonConvert.DeserializeObject<DistrictNodesResult>(data);
                    if (id == "")
                        BindTree(result.data);
                }
                catch (Exception exception)
                {
                    _Logger.Error(exception);
                }
            });
        }

        private void DeleteDistrict(DistrictNode node)
        {
            var kernel = DI.Get<Kernel>();
            var resoure = UrlManager.DeleteDistrict + (node.id.Length > 0 ? $"/{node.id}" : "");
            var request = new RestRequest(resoure, Method.DELETE);
            request.AddHeader("X-Token", kernel.Token);
            kernel.Client.ExecuteAsync(request, response =>
            {
                var data = response.Content;
                try
                {
                    _Logger.Debug(data);
                    var result = JsonConvert.DeserializeObject<BaseResult>(data);
                    MessageBox.Show(result.msg,result.errcode==0?"成功":"失败");
                }
                catch (Exception exception)
                {
                    _Logger.Error(exception);
                }
            });
        }

        private string ChangeToken(string kernelToken)
        {
           var token =  JwtHelper.Decode<Token>(kernelToken);
            token.payload.areaid = _ProjecCombox.SelectedValue.ToString();
            token.payload.id = "deb09192-45f9-44b6-ac3e-7f0bc3f5118f";
            token.payload.role = "操作员";
            return JwtHelper.Encode(token);
        }

        private void BindTree(DistrictNodesData data)
        {
            Invoke((EventHandler)delegate {
                JsonTreeViewHelper.BindTreeView(_TreeView, data);
            });
        }
        public void BindSite(string id="")
        {
            var kernel = DI.Get<Kernel>();
            var resoure = UrlManager.GetAreaUser + (id.Length > 0 ? $"/{id}" : "");
            var request = new RestRequest(resoure, Method.GET);
            request.AddHeader("X-Token", kernel.Token);
            kernel.Client.ExecuteAsync(request, response =>
            {
                var data = response.Content;
                try
                {
                    _Logger.Debug(data);
                    var result = JsonConvert.DeserializeObject<AreaOperatorResult>(data);
                    var list = new Dictionary<string, string>();
                    result?.data.siteList.ForEach(s => list[s.id] = s.siteName);
                    BindList(_ProjecCombox, list);
                }
                catch (Exception exception)
                {
                    _Logger.Error(exception);
                }
            });
        }

        private void BindList(ComboBox comboBox, Dictionary<string, string> value)
        {
            Invoke((EventHandler)delegate
            {
                var item = value.Select(a => new
                {
                    key = a.Key,
                    value = a.Value
                });
                comboBox.DataSource = item.ToList();
                comboBox.DisplayMember = "value";
                comboBox.ValueMember = "key";
            });
        }
    }
}
